//
//  WordViewController.m
//  高仿萝卜书摘
//
//  Created by 谢俊逸 on 2016/11/21.
//  Copyright © 2016年 谢俊逸. All rights reserved.
//

#import "WordViewController.h"
#import "EssenceTableViewController.h"
#import "OptionalTableViewController.h"
#import "AttentionTableViewController.h"
#import "XJYPaggingNavBar.h"
#import "XJYHeader.h"
#import "PYSearch.h"

@interface WordViewController ()<UIScrollViewDelegate,PYSearchViewControllerDelegate>
/**
 * scrollView
 */
@property (nonatomic,strong) UIScrollView *scrollView;
/**
 *  显示title集合的容器
 */
@property (nonatomic, strong) XJYPaggingNavBar *paggingNavbar;

/**
 *  标识当前页码
 */
@property (nonatomic, assign) NSInteger currentPage;





@end






@implementation WordViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    [self setupAllChildViewControllers];
    [self setupScrollView];
    [self addAllChildViewsInScrollView];
    [self setupPaggingNavbar];
    [self setupNavigationBar];
    
    


}

-(void)viewDidAppear:(BOOL)animated{
    //viewDidLoad 太早了 视图还没加载进去，所以要在视图在窗口加载完之后再设置初始的contentOffset和currentPage
    [self setupInitialScrollViewContentOffset];
    [self setupInitialPaggingNavbar];
    

}

- (void)setupInitialPaggingNavbar{
    self.paggingNavbar.contentOffset = _scrollView.contentOffset;
    self.paggingNavbar.currentPage = 1;
}

- (void)setupInitialScrollViewContentOffset{
    _scrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
}

- (void)setupNavigationBar{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"AddUserWhiteIcon-Small"] highImage:[UIImage imageNamed:@"AddUserWhiteIcon-Small"] target:self action:@selector(addUserClicked:)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"PlusWplusWIcon-Small"] highImage:[UIImage imageNamed:@"PlusBplusWIcon-Small"] target:self action:@selector(PlusClicked:)];
    
}


- (void)addAllChildViewsInScrollView{
    [self addChildVcViewIntoScrollView:0];
    [self addChildVcViewIntoScrollView:1];
    [self addChildVcViewIntoScrollView:2];
}
- (void)setupPaggingNavbar{
    //设置titleView
    self.navigationItem.titleView = self.paggingNavbar;
    //设置paggingNavbar当前页面
    self.paggingNavbar.currentPage = 0;
    //设置标题
    self.paggingNavbar.titles = @[self.childViewControllers[0].title,self.childViewControllers[1].title,self.childViewControllers[2].title];
    //设置初始偏移量
    //self.paggingNavbar.contentOffset = CGPointMake(375, 0);
    //paggingNavbar 加载数据 也就是标题喽
    [self.paggingNavbar reloadData];
}
- (void)setupAllChildViewControllers{

    [self addChildViewController:[[AttentionTableViewController alloc]init]];
    self.childViewControllers[0].title = @"关注";
    [self addChildViewController:[[EssenceTableViewController alloc]init]];
    self.childViewControllers[1].title = @"精华";
    [self addChildViewController:[[OptionalTableViewController alloc]init]];
    self.childViewControllers[2].title = @"自选";

}

-(void) setupScrollView{
    // 不允许自动修改UIScrollView的内边距
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.frame = self.view.bounds;
    scrollView.delegate = self;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.pagingEnabled = YES;
    scrollView.scrollsToTop = NO; // 点击状态栏的时候，这个scrollView不会滚动到最顶部
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    self.scrollView.delegate = self;
    
    // 添加子控制器的view
    NSUInteger count = self.childViewControllers.count;
    CGFloat scrollViewW = self.view.frame.size.width;
    //y上没有内容，所以上下拖动不会调用 scrollDelegate
    scrollView.contentSize = CGSizeMake(count * scrollViewW, 0);



}

#pragma mark - 其他
/**
 *  添加第index个子控制器的view到scrollView中
 */

- (void)addChildVcViewIntoScrollView:(NSUInteger)index
{
    UIViewController *childVc = self.childViewControllers[index];
    
    // 如果view已经被加载过，就直接返回
    if (childVc.isViewLoaded) return;
    
    // 取出index位置对应的子控制器view
    UIView *childVcView = childVc.view;
    
    // 设置子控制器view的frame
    CGFloat scrollViewW = self.scrollView.bounds.size.width;
    childVcView.frame = CGRectMake(index * scrollViewW, 0, scrollViewW, self.scrollView.bounds.size.height);
    // 添加子控制器的view到scrollView中
    [self.scrollView addSubview:childVcView];
}



//  得到当前的 currentPage
- (NSInteger)currentPage {
    long currentPage = lround( _scrollView.contentOffset.x / CGRectGetWidth(_scrollView.frame) );
    return currentPage;
}
#pragma mark - ScrollView Events -
//开始滚动调用该方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)aScrollView {
    
}
//在滚动视图中拖动结束时通知代理。
//滚动视图在用户的手指在拖动内容之后触摸时发送此消息。 UIScrollView的减速属性控制减速。
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{


}

//告诉代表滚动视图已经结束减速滚动运动。
//当滚动移动停止时，滚动视图调用此方法。 UIScrollView的减速属性控制减速。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    long currentPage = self.currentPage;
    self.currentPage = currentPage;
    self.paggingNavbar.currentPage = currentPage;
    
}


//当用户滚动接收器中的内容视图时告诉代表。
//委托通常实现这种方法来获取来自scrollView的内容偏移的变化，并绘制内容视图的受影响部分。
//拖动过程中一直调用。
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.paggingNavbar.contentOffset = scrollView.contentOffset;

}

//paggingNavbar 实际上是  titleView
- (XJYPaggingNavBar *)paggingNavbar {
    if (!_paggingNavbar) {
        _paggingNavbar = [[XJYPaggingNavBar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds) / 2.0, 44)];
        _paggingNavbar.backgroundColor = [UIColor clearColor];
    }
    return _paggingNavbar;
}


#pragma mark NavationBarClicked
-(void)addUserClicked:(id)leftBarItem{
    NSLog(@"leftBarItemClicked");

}

-(void)PlusClicked:(id)rightBarItem{
    NSLog(@"rightBarItemClicked");
}


#pragma mark - PYSearchViewControllerDelegate
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length) { // 与搜索条件再搜索
        // 根据条件发送查询（这里模拟搜索）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // 搜素完毕
            // 显示建议搜索结果
            NSMutableArray *searchSuggestionsM = [NSMutableArray array];
            for (int i = 0; i < arc4random_uniform(5) + 10; i++) {
                NSString *searchSuggestion = [NSString stringWithFormat:@"搜索建议 %d", i];
                [searchSuggestionsM addObject:searchSuggestion];
            }
            // 返回
            searchViewController.searchSuggestions = searchSuggestionsM;
        });
    }
}


@end
